#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <ctime>

#define MAXNFDS 1024

// 初始化服务端的监听端口
int initserver(int port);

int main(int argc, char* argv[]){
    if(argc != 2){
        printf("usage: ./tcpselect port\n");
        return -1;
    }

    // 初始化服务端用于监听的socket
    int listensock = initserver(atoi(argv[1]));
    printf("listensock=%d\n", listensock);
    if(listensock < 0){
        printf("initserver() failed.\n");
        return -1;
    }

    struct pollfd fds[MAXNFDS];         // fds存放需要监视的socket
    for(int i = 0; i < MAXNFDS; ++i){
        fds[i].fd = -1;                 // 初始化数组，把全部的fd设置为-1
    }
    // 把listensock和读事件添加到数组中
    fds[listensock].fd = listensock;
    fds[listensock].events = POLLIN;
    int maxfd = listensock;         // 记录集合中socket的最大值

// 测试select的水平触发
// sleep(10);
// int i = 1;

    while(true){
        int infds = poll(fds, maxfd+1, -1);

        // 调用失败
        if(infds < 0){
            printf("poll() failed.\n");
            perror("poll() failed");
            break;
        }

        // 超时
        if(infds == 0){
            printf("poll() timeout.\n");
            continue;
        }

        // 返回有事件发生时的socket数量
        for(int eventid = 0; eventid <= maxfd; ++eventid){
            if(fds[eventid].fd < 0) {continue;}                     // 如果fd为负，忽略
            if((fds[eventid].revents && POLLIN) == 0) {continue;}   // 如果没有事件，continue
            
            fds[eventid].revents = 0;       // 清空revents
            // 如果发生事件的是listensock，表示有新的客户端连上来
            if(eventid == listensock){
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int clientsock = accept(listensock, (struct sockaddr*)&client, &len);
                if(clientsock < 0){
                    perror("accept() failed");
                    continue;
                }
                printf("accept client(socket=%d) ok.\n", clientsock);

                // 修改fds数组中clientsock位置的元素
                fds[clientsock].fd = clientsock;
                fds[clientsock].events = POLLIN;
                fds[clientsock].revents = 0;
                if(maxfd < clientsock) {
                    maxfd = clientsock;
                }
            }
            // 如果发生事件的是listensock，表示有新的客户端连上来
            else{
                char buffer[1024];
                memset(buffer, 0, sizeof(buffer));
                if(recv(eventid, buffer, sizeof(buffer), 0) <= 0){
                    // 如果客户端的连接已断开
                    printf("%ld client(eventfd=%d) disconnected.\n", time(0), eventid);
                    close(eventid);                 // 关闭客户端socket
                    fds[eventid].fd = -1;

                    // 重新计算maxfd的值，只有当eventid==maxfd时才需要计算
                    if(eventid == maxfd){
                        for(int i = maxfd; i > 0; --i){
                            if(fds[i].fd != -1){
                                maxfd = i;
                                break;
                            }
                        }
                    }
                } 
                else{
                    send(eventid, buffer, strlen(buffer), 0);
                }
            }
        }
    }

    return 0;
}

// 初始化服务端的监听端口
int initserver(int port)
{
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if (sock < 0)
    {
        printf("socket() failed.\n"); return -1;
    }

    // Linux如下
    int opt = 1; unsigned int len = sizeof(opt);
    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,len);
    setsockopt(sock,SOL_SOCKET,SO_KEEPALIVE,&opt,len);

    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);

    if (bind(sock,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0 )
    {
        printf("bind() failed.\n"); close(sock); return -1;
    }

    if (listen(sock,5) != 0 )
    {
        printf("listen() failed.\n"); close(sock); return -1;
    }

    return sock;
}